import Vuex from 'vuex'

const admin = {
    state: {
        users: [],
        posts: []
    },
    mutations: {
        SET_USERS(state, user) {
            state.admin.users = user;
        },
        SET_POSTS(state, posts) {
            state.admin.posts = posts;
        }
    },
    actions: {
        async fetchUsers({commit}) {
            try {
                const response = await fetch("/api/users");
                const users = await response.json();
                commit("SET_USERS", users);
            } catch (error) {
                console.error(error);
            }
        },
        async fetchPosts() {
            const response = await fetch("/api/posts");
            this.posts = await response.json();
        },

        async likePost(postId) {
            await fetch(`/api/posts/${postId}/like`, {method: "POST"});
            this.posts = this.posts.map((post) => {
                if (post.id === postId) {
                    return {...post, likeCount: post.likeCount + 1};
                } else {
                    return post;
                }
            });
        },
        async createUser({dispatch}, user) {
            // create user logic
            dispatch("fetchUsers");
        },
        async deleteUser({dispatch}, userId) {
            // delete user logic
            dispatch("fetchUsers");
        },
        async editUser({dispatch}, {index, user}) {
            // edit user logic
            dispatch("fetchUsers");
        },
        async createPost({dispatch}, post) {
            // create post logic
            dispatch("fetchPosts");
        },
        async deletePost({dispatch}, postId) {
            // delete post logic
            dispatch("fetchPosts");
        },
        async approvePost({dispatch}, {index, post}) {
            // approve post logic
            dispatch("fetchPosts");
        },
        async rejectPost({dispatch}, {index, post}) {
            // reject post logic
            dispatch("fetchPosts");
        }
    }
};
const store = new Vuex.store({
    module: {
        admin
    }
})


